package net.lab1024.sa.admin.module.business.goods.service;

import lombok.RequiredArgsConstructor;
import net.lab1024.sa.admin.module.business.goods.dao.ProductStockMapper;
import net.lab1024.sa.admin.module.business.goods.domain.entity.ProductStock;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor  // Lombok注入依赖
public class StockService {

    private final ProductStockMapper stockMapper;

    /**
     * 扣减库存（无并发控制，故意留坑）
     * @param productId 商品ID
     * @return 扣减成功返回true，失败返回false
     */
    @Transactional  // 加事务（保证查询和更新在一个事务中，但不解决并发问题）
    public boolean decreaseStock(Long productId) {
        long threadId = Thread.currentThread().getId();
        String threadName = Thread.currentThread().getName();
        System.out.println("当前线程名称: " + threadName +"线程ID：" + threadId + " 开始扣减商品ID：" + productId);
        // 步骤1：查询当前库存
        ProductStock stock = stockMapper.selectByProductId(productId);
        if (stock == null || stock.getStock() <= 0) {
            System.out.println("库存不足，扣减失败");
            return false;
        }
        // 关键：加100ms延迟，放大并发冲突窗口
        try {
            Thread.sleep(100); // 模拟业务处理（比如校验订单、日志记录）
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
        // 步骤2：扣减库存（stock = stock - 1）
        int rows = stockMapper.decreaseStock(productId);
        System.out.println("扣减库存成功，剩余库存：" + (stock.getStock() - 1));
        return rows > 0;
    }
}